<template>
  <!-- <a-drawer
    title="快照"
    placement="right"
    width="100%"
    class="fra-drawer fra-drawer-s snapshot-box-drawer"
    :closable="true"
    :mask="false"
    :visible="snapshotVisible"
    @close="onClose"
  > -->

  <a-modal
    :mask-closable="false"
    :visible="snapshotVisibleF"
    title="维护数据快照 - Snapshot"
    :class="['c-dialog-box ',singlePage?'c-dialog-box-full':'']"
    :closable="!singlePage"
    :dialog-style="{height:'574px'}"
    :footer="null"
    :z-index="modalZIndexM"
    :width="1182"
    centered
    destroy-on-close
    @cancel="onClose"
  >
    <span slot="closeIcon" class="c-close-icon"><a-icon :component="require('@/assets/icon/close.svg')" /></span>

    <span v-if="!singlePage" class="new-page-btn" @click="goNewPageHandler(ssuuid)"><a-icon :component="require('@/assets/icon/newPage.svg')" /></span>
    <a-spin :spinning="snapshotLoading" class="c-dialog-search-box">
      <!-- info -->
      <a-row class="c-dialog-search-box-2">
        <a-col :span="2">
          <div class="fw-b fs-12 color-r">机号</div>
          <a class="fs-18 fw-b numbers" @click="setState({key:'flightLegHistoryVisible',payload:true})">{{ currentRow.tailnumber||'--' }}</a>
        </a-col>
        <a-col :span="3">
          <div class="fw-b fs-12 color-r">机队</div>
          <div class="fs-18 fw-b color-title numbers">{{ currentRow.fleet||'--' }}</div>
        </a-col>
        <a-col :span="19" class="pt-5">
          <!-- search -->
          <a-form-model ref="snapshot-box" layout="inline" :model="search">

            <!-- 筛选条件与查询 -->
            <a-form-model-item v-show="checkedFilter.includes(0)" label="">
              <ssReportType v-model="search.reportType" :placeholder="'报告名称'" value-key="templateName" name-key="templateName" :data-source="repReportTemplateListF" style="width: 130px" />

            </a-form-model-item>
            <!-- <a-form-model-item v-show="checkedFilter.includes(1)" label="">

              <groupName v-model="search.groupName" class="group-name-select-box" placeholder="数据收集" style="width: 130px" mode="multiple" />

            </a-form-model-item> -->
            <a-form-model-item v-show="checkedFilter.includes(2)" label="">

              <a-range-picker
                v-model="timeList"
                style="width: 260px"
                format="YYYY/MM/DD"
                value-format="YYYY/MM/DD"
                :disabled-date="disabledDate"
                :get-calendar-container="triggerNode =>triggerNode.parentNode"
              >
                <a-icon slot="suffixIcon" type="calendar" />
              </a-range-picker>
            </a-form-model-item>
            <!-- <a-date-picker

                placeholder="起始时间"
                :disabled-date="disabledStartDate"

              />

            <a-form-model-item v-show="checkedFilter.includes(3)" label="">
              <a-date-picker
                v-model="search.endTime"
                style="width: 130px"
                format="YYYY/MM/DD"
                value-format="YYYY/MM/DD 23:59:59"
                placeholder="结束时间"
                :disabled-date="disabledEndDate"
                :get-calendar-container="triggerNode =>triggerNode.parentNode"
              />
            </a-form-model-item> -->

            <a-form-model-item>
              <a-button type="primary" class="mr-10" ghost :loading="snapshotLoading" @click="resetSearchHandler">
                重置
              </a-button>
              <!-- <a-button type="primary" :loading="snapshotLoading" @click="getData">
                查询
              </a-button> -->

              <a-dropdown
                overlay-class-name="snapshot-filter-search"
                title="筛选条件"
                :visible="checkedFilterShow"
                :trigger="['click']"
                placement="bottomCenter"
                @visibleChange="handleClickChange"
              >
                <a-icon :component="require('@/assets/icon/Fleet_Status_Filter_Setting.svg')" class="cu-poin ml-16" />
                <div slot="overlay" class="c-dropdown-box">
                  <div class="c-dropdown-box-title">选择显示的筛选条件</div>
                  <a-checkbox-group v-model="checkedFilterTmp">
                    <a-row class="checked-filter-box ">
                      <a-col v-for="item in filterList" :key="item.label" class="notice-item-e" :span="24">
                        <a-checkbox :value="item.value">
                          {{ item.label }}
                        </a-checkbox>
                      </a-col>
                    </a-row>
                  </a-checkbox-group>
                  <div class="d-flex jc-center">
                    <a-button size="small" class="mr-5" @click="handleClickChange(false)">取消</a-button>
                    <a-button size="small" class="ml-5" type="primary" @click="filterChangeSave">确定</a-button>
                  </div>
                </div>
              </a-dropdown>
            </a-form-model-item>
          </a-form-model>
        </a-col>
      </a-row>

    </a-spin>

    <!-- table -->
    <a-spin :spinning="snapshotLoading" class="c-dialog-main-box beauty-scroll">
      <a-row :gutter="12" class="width-change-box-ss">
        <a-col :span="repShow?12:24" class="left-menu-ss">
          <vxe-grid
            ref="xTable1"
            class="snapshot-vxe-table"
            show-overflow
            resizable
            :row-class-name="rowVxeClassHandler"
            highlight-hover-row
            :columns="snapshotColumns"
            :data="snapshotList"
            :height="vxeH"
            :sort-config="{trigger: 'cell'}"
            @cell-click="customRow"
          />
        </a-col>
        <dragAdjustWidth v-show="repShow" :style-loc="styleLoc" />
        <a-col v-if="repShow" :span="repShow?12:24" class="snapshot-data-main-box right-menu-ss">
          <a-tabs v-model="repTab" @change="changeTabHandler">
            <a-tab-pane key="2" tab="格式化数据" force-render />
            <a-tab-pane key="1" tab="原始数据" />

          </a-tabs>

          <div v-show="repTab==='1'" class="snapshot-data-s snapshot-data-s1 beauty-scroll">
            <div style="margin-top:-24px">
              {{ repShowData.content }}
            </div>
          </div>

          <div v-show="repTab!=='1'" class="snapshot-data-s snapshot-data-s2 beauty-scroll snapshot-data-s-wn scroll-hidden">
            <a-spin :spinning="repAnalysisJsonLoading" class="w-100" />
            <!-- <div v-html="repAnalysisJsonData" /> -->
            <iframe id="rep-iframe" class="iframe" frameborder="0" />

          </div>

        </a-col>
      </a-row>

    </a-spin>

  </a-modal>
  <!-- </a-drawer> -->
</template>

<script>
import { mapState, mapActions, mapGetters, mapMutations } from 'vuex';
// import reportType from '@/pages/components/reportType';
import ssReportType from '@/pages/components/ssReportType';
// import groupName from '@/pages/components/groupName';
import { debounce } from '@/utils/util.js';
import dragAdjustWidth from '@/pages/components/dragAdjustWidth';
export default {
  components: {
    ssReportType,
    // groupName,
    dragAdjustWidth
  },
  props: {
    // currentRow: {
    //   type: Object,
    //   default: () => {}
    // },
    snapshotVisible: {
      type: Boolean,
      default: false
    },
    reportHandler: {
      type: Function,
      default() {
        return function() {};
      }
    }
  },
  data() {
    return {
      timeList: [],
      styleLoc: {
        box: 'width-change-box-ss',
        left: 'left-menu-ss',
        right: 'right-menu-ss'
      },
      repId: -1,
      modalZIndexM: 2000,
      repTab: '2',
      iframeScrollTop: 0,
      repShowData: {},
      currentRow: {},
      search: {
        // startTime: '',
        // endTime: '',
        groupName: [],
        reportType: undefined
      },
      activeIndex: [-1],
      checkedFilterShow: false,
      checkedFilterTmp: [],
      checkedFilter: [0, 1, 2],
      ssuuid: '',
      filterList: [
        {
          value: 0,
          label: '报告类型'
        },
        // {
        //   value: 1,
        //   label: '数据收集'
        // },
        {
          value: 2,
          label: '时间范围'
        }
      ],

      repShow: false,
      vxeH: '395px'
    };
  },

  computed: {
    ...mapState('fraMonitoring', [
      'snapshotLoading',
      'snapshotList',
      'repAnalysisJsonData',
      'repAnalysisJsonLoading',
      'modalZIndex'
    ]),
    ...mapState('templateManagement', [
      'repReportTemplateList'

    ]),
    ...mapGetters('fraMonitoring', [
      'snapshotVisibleF'
    ]),
    repReportTemplateListF() {
      return [...this.repReportTemplateList].sort((a, b) => (a?.templateName ?? '').localeCompare((b?.templateName ?? ''))).filter(item => item.smi === 'ENG');
    },

    singlePage() {
      return ((this.$route.meta?.singlePage ?? false) && this.$route.query.rp === 'snapshotVisible');
    },
    snapshotColumns() {
      const nc = [
        {
          title: '航班',
          align: 'left',
          dataIndex: 'flightNo',
          width: 100,
          slots: {
            default: ({ row }) => {
              return row.flightNo ? [<a onClick={(e) => this.reportHandler({ ...this.currentRow, ...row }, 'flightLegDetailsVisible')}>{row.flightNo}</a>] : '--';
            }
          }
        },
        {
          title: '报告名称',
          align: 'left',
          dataIndex: 'templateName',
          width: 190,
          slots: {
            default: ({ row }) => {
              return row.templateName || '--';
            }

          }
        },
        {
          title: '数据组(DCG)',
          align: 'left',
          dataIndex: 'groupName',
          width: 130,
          slots: {
            default: ({ row }) => {
              return row.groupName || '--';
            }
          }
        },
        {
          title: '报告时间',
          dataIndex: 'providerTime',
          align: 'left',
          width: 150,
          slots: {
            default: ({ row }) => {
              return row.providerTime ? this.$moment.utc(row.providerTime).format('YYYY-MM-DD HH:mm:ss') : '--';
            }
          }
        }
      ];

      if (!this.repShow) {
        nc.splice(0, 0, {
          title: '航段',
          align: 'left',
          dataIndex: 'leg',
          width: 80,
          slots: {
            default: ({ row }) => {
              return row.leg ?? '--';
            }
          }
        });

        nc.splice(2, 0, {
          title: '航段日期',
          align: 'left',
          dataIndex: 'legDate',
          slots: {
            default: ({ row }) => {
              return row.latestAcarsTime ? this.$moment.utc(row.latestAcarsTime).format('YYYY-MM-DD HH:mm:ss') : '--';
            }
          }
        },
        {
          title: '起飞机场',
          align: 'left',
          dataIndex: 'dep',
          width: 80,
          slots: {
            default: ({ row }) => {
              return [<a onClick={(e) => this.airportInfoHandler(e, row.dep)}>{row.dep || '--'}</a>];
            }
          }
        },
        // {
        //   dataIndex: 'arrow',
        //   align: 'left',
        //   width: 48,
        //   slots: {
        //     default: ({ row }) => {
        //       return [<span class='c-arrow color-s'>····</span>];
        //     }
        //   }
        // },
        {
          title: '落地机场',
          dataIndex: 'arr',
          align: 'left',
          width: 80,
          slots: {
            default: ({ row }) => {
              return [<a onClick={(e) => this.airportInfoHandler(e, row.arr)}>{row.arr || '--'}</a>];
            }
          }
        },
        {
          title: '报文类型',
          align: 'left',
          dataIndex: 'reportType',
          slots: {
            default: ({ row }) => {
              return row.category || '--';
            }
          }
        },
        {
          title: '版本号',
          align: 'left',
          dataIndex: 'version',
          width: 70,
          slots: {
            default: ({ row }) => {
              return row.version || '--';
            }
          }
        }
        );
      }
      return nc;
    }
  },
  watch: {
    'search': {
      handler(nv) {
        if (this.snapshotVisibleF) {
          this.debounceGet();
        }
      },
      deep: true
    },
    'timeList': {
      handler(nv) {
        if (this.snapshotVisibleF) {
          this.debounceGet();
        }
      },
      deep: true
    },
    'snapshotVisibleF': {
      handler(nv) {
        if (nv) {
          this.setState({ key: 'modalZIndex', payload: this.modalZIndex + 1 });
          this.modalZIndexM = this.modalZIndex;
          this.ssuuid = this.$route?.query?.ssuuid ?? new Date().getTime();
          const lsRow = sessionStorage.getItem(`ss${this.ssuuid}`) ?? localStorage.getItem('scRow') ?? localStorage.getItem('row');
          this.currentRow = JSON.parse(lsRow) ?? {};

          if (this.$store.state.setting.openType === '_blank' && !this.$route?.query?.ssuuid) {
            this.goNewPageHandler(this.ssuuid);
            this.setState({ key: 'snapshotVisible', payload: false });
          } else {
            this.vxeH = this.singlePage ? `${document.body.clientHeight - 180}px` : '395px';
            this.repShow = false;

            this.getRepReportTemplateList({ pageNum: 1, pageSize: 9999 });

            // this.search.startTime = '';
            // this.search.endTime = '';
            this.timeList = [];
            this.search.reportType = undefined;
            this.search.groupName = [];
            this.debounceGet();
          }
        } else {
          if (nv === false && this.$store.state.setting.openType !== '_blank') {
            localStorage.removeItem('scRow');
          }
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.timeList = [];
    this.getRepReportParamGroup();
  },
  methods: {
    ...mapActions('fraMonitoring', [
      'getListSnapshotByParam',
      'repAnalysisJson',
      'getRepReportParamGroup'
    ]),
    ...mapActions('templateManagement', [
      'getRepReportTemplateList'

    ]),
    ...mapMutations('fraMonitoring', [
      'setState'
    ]),
    debounceGet: debounce(function() { this.getData(); }, 300),
    resetSearchHandler() {
      // this.search.startTime = '';
      // this.search.endTime = '';
      this.search.reportType = undefined;
      this.search.groupName = [];
      this.timeList = [];
      // this.getData();
    },
    // 筛选弹框
    handleClickChange(visible) {
      if (visible) {
        this.checkedFilterTmp = [...this.checkedFilter];
      }
      this.checkedFilterShow = visible;
    },
    // 保存选择的筛选条件
    filterChangeSave() {
      this.checkedFilterShow = false;
      this.checkedFilter = [...this.checkedFilterTmp];
    },

    // 点击行
    customRow({ row, rowIndex }) {
      this.repId = -1;
      if (this.activeIndex[0] === rowIndex) {
        this.repShow = false;
        this.activeIndex[0] = [-1];
        document.querySelector('.left-menu-ss').style.width = '50%';
      } else {
        this.repShow = true;
        this.activeIndex = [rowIndex];
        this.repShowData = { ...row };
        this.repShowData.content = '\r\n' + row.content;
        if (this.repTab === '2') {
          this.changeTabHandler();
        }

        this.$nextTick(() => {
          try {
            if (document.querySelector('.snapshot-data-s1')) {
              document.querySelector('.snapshot-data-s1').scrollTop = 0;
              const iframe = document.getElementById('rep-iframe');
              if (iframe && iframe.contentWindow) {
                iframe.contentWindow.document.body ? iframe.contentWindow.document.body.scrollTop = 0 : '';
                this.iframeScrollTop = 0;
              }
            }
          } catch (error) {
            //
          }
        });
      }
    },
    rowVxeClassHandler({ rowIndex }) {
      let className = ['light-row'];
      if (rowIndex % 2 === 1) className = ['light-row'];
      (this.activeIndex[1] || this.activeIndex[0]) === rowIndex
        ? className.push('active-row-c')
        : className.push('active-row-n');
      return className;
    },
    async changeTabHandler() {
      const { repReportId, templateName, templateType, version } = this.repShowData;
      if (this.repTab === '2') {
        let type = 1;
        switch (templateType) {
          case 'DFD':
            type = 1;
            break;

          case 'ENG':
            type = 2;
            break;
        }
        const params = {
          repReportId,
          templateName,
          templateType: type,
          version
        };
        if (this.repId !== repReportId) {
          try {
            const iframe = document.getElementById('rep-iframe');
            if (iframe && iframe.contentWindow) {
              iframe.contentWindow.document.write('');
            }
          } catch (error) {
            //
          }
          this.iframeScrollTop = 0;
          await this.repAnalysisJson(params);
          this.$nextTick(() => {
            const iframe = document.getElementById('rep-iframe');
            const iframeStyle = `<style type=\"text/css\">
          ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
          }
          ::-webkit-scrollbar-thumb {
            border-radius: 1em;
            background-color: #c6ccd7;
          }
          ::-webkit-scrollbar-track {
            border-radius: 1em;
            background-color: transparent;
          }
        </style>`;
            iframe.contentWindow.document.write(iframeStyle + this.repAnalysisJsonData);
            iframe.contentWindow.document.close();
            document.querySelector('.snapshot-data-s1').scrollTop = 0;
          });
          this.repId = repReportId;
        } else {
          this.$nextTick(() => {
            try {
              const iframe = document.getElementById('rep-iframe');
              iframe.contentWindow.document.body.scrollTop = this.iframeScrollTop;
            } catch (error) {
              //
            }
          });
        }
      } else {
        try {
          const iframe = document.getElementById('rep-iframe');
          this.iframeScrollTop = iframe.contentWindow.document.body.scrollTop;
        } catch (error) {
          //
        }
      }
    },
    // 当drawer点击关闭
    onClose() {
      this.$emit('close', 'snapshotVisible');
      this.activeIndex = [-1];
      this.repTab = '2';
      this.repId = -1;
      // this.drawerVisible = false;
    },
    // 不可选时间
    // disabledStartDate(startValue) {
    //   const endValue = this.search.endTime;
    //   if (!startValue || !endValue) {
    //     return false;
    //   }
    //   return startValue.valueOf() > new Date(endValue).getTime().valueOf();
    // },
    // disabledEndDate(endValue) {
    //   const startValue = this.search.startTime;
    //   if (!endValue || !startValue) {
    //     return false;
    //   }
    //   return new Date(startValue).getTime().valueOf() >= endValue.valueOf();
    // },
    airportInfoHandler(e, code) {
      e.stopPropagation();
      this.setState({ key: 'airportInfoVisible', payload: true });
      localStorage.setItem('apInfoCode', code);
    },
    disabledDate(current) {
      // Can not select days before today and today
      return current && current > this.$moment().endOf('day');
    },

    // 获取数据
    getData() {
      const { model, tailnumber } = this.currentRow;
      const params = {
        reportType: this.search.reportType ? this.search.reportType : undefined,
        groupName: this.search.groupName?.length > 0 ? this.search.groupName : undefined,
        startTime: this.timeList[0] ? this.timeList[0] + ' 00:00:00' : undefined,
        endTime: this.timeList[1] ? this.timeList[1] + ' 23:59:59' : undefined,
        legId: this.currentRow?.id ?? this.currentRow?.legId ?? '',
        model,
        tailNumber: tailnumber
      };
      this.getListSnapshotByParam(params);
    },
    goNewPageHandler(ssuuid = '') {
      sessionStorage.setItem(`ss${ssuuid}`, JSON.stringify(this.currentRow));

      const routeData = this.$router.resolve({
        path: '/reportsLayout',
        query: {
          rp: 'snapshotVisible',
          ssuuid
        }
      });

      window.open(routeData.href, '_blank');
    }
  }
};
</script>

<style lang="less" scoped>
@import './index.less';
</style>

<style  lang="less">
@import "../../index.less";

.snapshot-box-drawer{
  transform: translate(0) !important;
}
.checked-filter-box {
  width: 128px;
}
.snapshot-filter-search{
  z-index: 1052;
}
.fld-pre-main-box table{
  width: 100%;
}
</style>
